package com.dome.config.threadpool;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Configuration
@EnableAsync
public class CustomizeThreadPool{
    /**
     * 核心线程数
     */
    @Value("${task.pool.corePoolSize}")
    private int corePoolSize;

    /**
     * 最大线程数
     */
    @Value("${task.pool.maxPoolSize}")
    private int maxPoolSize;

    /**
     * 线程空闲时间
     */
    @Value("${task.pool.keepAliveSeconds}")
    private int keepAliveSeconds;

    /**
     * 任务队列容量（阻塞队列）
     */
    @Value("${task.pool.queueCapacity}")
    private int queueCapacity;

    private ThreadPoolTaskExecutor executor;
 
    @Bean("customizeThreadPoolTask")
    public Executor doConfigCustomizeThreadPool() {
        executor = new ThreadPoolTaskExecutor();
        //核心线程池大小
        executor.setCorePoolSize(this.corePoolSize);
        //最大线程数
        executor.setMaxPoolSize(this.maxPoolSize);
        //队列容量
        executor.setQueueCapacity(this.keepAliveSeconds);
        //活跃时间
        executor.setKeepAliveSeconds(this.queueCapacity);
        //线程名字前缀
        executor.setThreadNamePrefix("test-asyncExecutor");
         /*
            当poolSize已达到maxPoolSize，如何处理新任务（是拒绝还是交由其它线程处理）
            CallerRunsPolicy：不在新线程中执行任务，而是由调用者所在的线程来执行
         */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}